<?php
/**
 * Created by PhpStorm.
 * User: sojo
 * Date: 2017/12/28
 * Time: 14:17
 */

namespace App\Http\Admin\Administration\Models;

use App\Api\OA\Personnel\Models\Personnel;
use App\Eloquent\Job\Resume\Resume;
use App\Eloquent\Oa\Contacts;
use App\Eloquent\Oa\FlowFile;
use App\Http\Admin\Personnel\Models\PassFlow;
use App\Repositories\OA\FlowConfigProcessRepository;
use Framework\BaseClass\Http\Admin\Model;
use Framework\Services\Push\JPush\JPushService;

class Workflow extends Model
{
    const RELATE_TYPE_FLOW_DOCUMENT = 1;
    const RELATE_TYPE_FLOW_LEAVE = 2;
    const RELATE_TYPE_FLOW_SEAL_USE = 3;
    const RELATE_TYPE_FLOW_CAR_USE = 4;
    const RELATE_TYPE_FLOW_RESIGN = 5;
    const RELATE_TYPE_FLOW_TRANSFER_POST = 6;
    const RELATE_TYPE_FLOW_REIMBURSE = 7;  // 报销
    const RELATE_TYPE_FLOW_EGRESS = 8;     // 外出
    const RELATE_TYPE_FLOW_BUSINESS_TRIP = 9; // 出差
    const RELATE_TYPE_FLOW_HOLIDAY_SHIFT = 10; // 调休
    const RELATE_TYPE_FLOW_WORKDAY_SHIT = 11;  // 补勤
    const RELATE_TYPE_FLOW_OVERTIME_PAY = 12;  // 加班费
    const RELATE_TYPE_FLOW_RECEIVE_APPLY_FOR = 13;  // 领用申请
    const RELATE_TYPE_FLOW_PROCUREMENT = 14;  // 采购申请
    const RELATE_TYPE_FLOW_CONTENT = 15;  // 合同
    const RELATE_TYPE_FLOW_PETTY_CASH = 16;  // 备用金
    const RELATE_TYPE_FLOW_SYSTEM_SOLUTIONS = 17;  // 制度方案
    const RELATE_TYPE_FLOW_RECEUITMENT_NEEDS = 18;  // 招聘需求
    const RELATE_TYPE_FLOW_REWARD_AND_PUNISH = 19;  // 奖罚申报
    const RELATE_TYPE_FLOW_DIMISSION = 20;  // 离职
    const RELATE_TYPE_FLOW_BECOME_PROMOTE_SALARY = 21;  // 转正晋升调薪
    const RELATE_TYPE_FLOW_REPLENISH_SIGN = 22;  // 补签
    const RELATE_TYPE_FLOW_INTERVIEW = 23;  // 面试
    const RELATE_TYPE_FLOW_TAKING_WORK = 24;  // 入职
    const RELATE_TYPE_FLOW_PURCHASE_APPLICATION = 26;  // 采购申请
    const RELATE_TYPE_FLOW_RETURN_PURCHASE_APPLICATION = 27;  // 退货申请

    /**
     * 创建工作流
     * @author sojo
     */
    public function create($saveData)
    {
        $workflow = new \App\Eloquent\Oa\Workflow($saveData);

        xAssert($workflow->save());

        return $workflow;
    }

    /**
     * 处理工作流
     * @author sojo
     * @param int $workflowId 工作流ID
     * @param int $disposeCode 处理编码
     * @param int $operatorId 经办人ID
     * @param int $assigneeId 受委托人ID
     * @param string $opinion 处理意见
     * @param string $imageUrl
     * @param string $enclosureUrl
     * @throws \Exception
     */
    public function handle($workflowId, $disposeCode, $operatorId, $assigneeId = 0, $opinion = '', $imageUrl = '', $enclosureUrl = '',$extra_info=[])
    {
        \DB::beginTransaction();
        try {
            $workflow = \App\Eloquent\Oa\Workflow::find($workflowId);

            //易管通需要，当前操作人
            $curUserId = $workflow->assignee_id;

            //如果流程已经结束，拒绝再提交
            if($workflow['dispose_code'] == 1100 || $workflow['dispose_code'] == 1200){
                $re = [
                    'code' => 1,
                    'message' => '数据已提交，请刷新页面',
                ];
                echo \GuzzleHttp\json_encode($re);die();
            }

            if (empty($assigneeId)) $assigneeId = 0;
            if (empty($opinion)) $opinion = '';

            // 如果$disposeCode == 1100，则需要判断是否还有后续
            if ($disposeCode === 1100) {
                $flowConfigProcess = new FlowConfigProcessRepository();

                if ($workflow->oa_flow_config_process_id > 0) {
                    $pid = $flowConfigProcess->find(['id' => $workflow->oa_flow_config_process_id])->pid;
                    // TODO:目前只做单一流程，后续如同一步中需要多人审批时，需要在此进行判断
                    if ($pid > 0) {
                        $assigneeId = $flowConfigProcess->find(['id' => $pid])->operator_id;
                        $disposeCode = 1002;
                        $saveData['oa_flow_config_process_id'] = $pid;
                    }
                }
            }

            $saveData['dispose_code'] = $disposeCode;
            $saveData['assignee_id'] = $assigneeId;

            if ($disposeCode === 1201) {
                if ($workflow->dispose_code !== 1000) xThrow(ERR_OA_WORKFLOW_HAVE_ACCEPTED);
            } else {
                $saveData[] = $workflow->step + 1;
            }

            $workflow->fill($saveData);

            xAssert($workflow->save());

            $workflowLog = new WorkflowLog();
            $workflowLog->add($workflow->id, $disposeCode, $operatorId, $assigneeId, $opinion, $imageUrl, $enclosureUrl);

            \DB::commit();


            //易管通申请加入消息模块
            if(in_array($workflow->related_type,array(26,27))){
                if($disposeCode == 1002){//同意（不结束）
                    //给申请人发消息
                    $data           = [
                        'company_id'=> $workflow->oa_company_id,
                        'privilege_id'=> '',
                        'form_user_id'=> $curUserId,
                        'to_user_id'=> $workflow->creator_id,
                        'foreign_key'=> $workflow->id,
                        'type'=>18,
                        'type_id'=>$workflow->id,
                        'title'=>'采购申请',
                        'content'=>'申请有新的动态'
                    ];
                    if(!isset($extra_info['is_stop_flow']) || $extra_info['is_stop_flow'] == 0){
                        \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($data);
                    }

                    //给下一步的审核人发信息
                    //给申请人发消息
                    $data           = [
                        'company_id'=> $workflow->oa_company_id,
                        'privilege_id'=> '',
                        'form_user_id'=> $curUserId,
                        'to_user_id'=> $assigneeId,
                        'foreign_key'=> $workflow->id,
                        'type'=>18,
                        'type_id'=>$workflow->id,
                        'title'=>'采购申请',
                        'content'=>'申请有新的动态'
                    ];
                    if(!isset($extra_info['is_stop_flow']) || $extra_info['is_stop_flow'] == 0){
                        \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($data);
                    }


                }elseif($disposeCode == 1200){
                    if($workflow->related_type == 26){
                        //材料验收不合格拒收
                        //采购单号、供应商、供应商联系电话（可直接拨打）、采购总金额、拒收理由

                        //获取所需数据
                        $purchaseOrderNum = $supplierName = $supplierTel =  $rejectContent = '';
                        $purchaseSumPrice = 0;
                        $purchaseId = $workflow['related_id'];
                        $purchaseRow = \App\Eloquent\Ygt\Purchase::where(['id'=>$purchaseId])->first();
                        if($purchaseRow){
                            $purchaseOrderNum =  \App\Engine\Common::changeSnCode($purchaseRow['purchase_number']);

                            $purchaseMaterialList = \App\Eloquent\Ygt\PurchaseMaterial::where(['purchase_id'=>$purchaseId])->get();
                            foreach ($purchaseMaterialList as $purchaseMaterialRow){
                                $purchaseSumPrice += $purchaseMaterialRow['num'] * $purchaseMaterialRow['price'];
                            }

                            $purchaseSumPrice = "¥".sprintf("%.2f",$purchaseSumPrice);
                        }

                        $supplierId = $purchaseRow['supplier_id'];
                        $supplierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$supplierId])->first();
                        if($supplierRow){
                            $supplierName = $supplierRow['title'];
                            $supplierTel = $supplierRow['contact_mobile'];
                        }

                        $messageContent = "采购单号：{$purchaseOrderNum}rnrn";
                        $messageContent .= "供应商：{$supplierName}rnrn";
                        $messageContent .= "供应商联系电话：{$supplierTel}rnrn";
                        $messageContent .= "采购总金额：{$purchaseSumPrice}rnrn";
                        $messageContent .= "拒收理由：{$rejectContent}";

                        //发送给采购员
                        $data           = [
                            'company_id'=> $workflow->oa_company_id,
                            'privilege_id'=> '',
                            'form_user_id'=> $curUserId,
                            'to_user_id'=> $purchaseRow['uid'],
                            'foreign_key'=> $workflow->id,
                            'type'=>18,
                            'type_id'=>$workflow->id,
                            'title'=>'采购申请',
                            'content'=>$messageContent,
                            'theme'=>'材料拒收'
                        ];
                        \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($data);
                    }


                }else{
                    //给申请人发消息
                    $data           = [
                        'company_id'=> $workflow->oa_company_id,
                        'privilege_id'=> '',
                        'form_user_id'=> $curUserId,
                        'to_user_id'=> $workflow->creator_id,
                        'foreign_key'=> $workflow->id,
                        'type'=>18,
                        'type_id'=>$workflow->id,
                        'title'=>'采购申请',
                        'content'=>'申请有新的动态'
                    ];
                    if(!isset($extra_info['is_stop_flow']) || $extra_info['is_stop_flow'] == 0){
                        \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($data);
                    }
                }

            }


            // 流程通过后，对接相关业务
            if ($disposeCode === 1100) {
                switch ($workflow->related_type) {
                    case 22:        // 补签
                        // TODO
                        break;
                    case 24:        // 入职
                        // 通过用户 ID 获取简历ID
                        $resumeInfo = Resume::where('user_id', $workflow->creatorInfo->user_id)->first();

                        $passFlow = new PassFlow();
                        $passFlow->addPersonnelFile($workflow->creator_id, $resumeInfo->id);
                        break;
                }
            }

            /* author:wenwenbin 2018-1-24  添加推送*/
            $related_type_str = self::getRelatedTypeStr($workflow['related_type']);
            $creator = Contacts::with('userInfo')->find($workflow['creator_id']);
            $assignee = Contacts::with('userInfo')->find($workflow['assignee_id']);
            $jPush = new JPushService();
            if ($disposeCode === 1100) {
                if ($creator && $creator->userInfo) {
                    $jPush->appSend(
                        [
                            $creator->userInfo->customer_name
                        ],
                        '您发起的' . $related_type_str . '审批已经通过', $related_type_str . '审批',
                        [
                            'type' => 1,
                            'ios_url' => 'OAApprovalMySendDetaileController',
                            'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                            'params' => ['from' => 'my', 'id' => $workflow['id']]
                        ]
                    );
                }
            } elseif ($disposeCode === 1200) {
                if ($creator  && $creator->userInfo) {
                    $jPush->appSend(
                        [
                            $creator->userInfo->customer_name
                        ],
                        '您发起的' . $related_type_str . '审批已被拒绝', $related_type_str . '审批',
                        [
                            'type' => 1,
                            'ios_url' => 'OAApprovalMySendDetaileController',
                            'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                            'params' => ['from' => 'my', 'id' => $workflow['id']]
                        ]
                    );
                }
            } elseif ($disposeCode === 1001) {
                if ($creator  && $creator->userInfo && $assignee) {
                    $jPush->appSend(
                        [
                            $creator->userInfo->customer_name
                        ],
                        '您发起的' . $related_type_str . '审批已被转派至' . $assignee->name . '处理，请注意查看', $related_type_str . '审批',
                        [
                            'type' => 1,
                            'ios_url' => 'OAApprovalMySendDetaileController',
                            'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                            'params' => ['from' => 'my', 'id' => $workflow['id']]
                        ]
                    );
                }
                if ($assignee  && $assignee->userInfo) {
                    $jPush->appSend(
                        [
                            $assignee->userInfo->customer_name
                        ],
                        '有人转派了一条' . $related_type_str . '审批给您，请及时查看', $related_type_str . '审批',
                        [
                            'type' => 1,
                            'ios_url' => 'OAWaitMyApprovalDetaileController',
                            'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                            'params' => ['from' => 'wait', 'id' => $workflow['id']]
                        ]
                    );
                }
            } elseif ($disposeCode === 1201) {
                if ($assignee && $assignee->userInfo) {
                    $jPush->appSend(
                        [
                            $assignee->userInfo->customer_name
                        ],
                        $creator->name . '发起的' . $related_type_str . '审批已撤销，请注意查看', $related_type_str . '审批',
                        [
                            'type' => 1,
                            'ios_url' => 'OAWaitMyApprovalDetaileController',
                            'android_url' => 'com.quanmai.jindun.ui.newoa.examine.waitmyexamine.ExamineDetailActivity',
                            'params' => ['from' => 'wait', 'id' => $workflow['id']]
                        ]
                    );
                }
            }
            /* author:wenwenbin 2018-1-24  添加推送*/
        } catch (\DebugError $e) {
            \DB::rollBack();
            xThrow($e->getCode());
        }

    }

    /**
     * 流程列表
     * @author LuLingFeng
     * @param $userId
     * @param $where
     * @param $paging
     * @return array
     */
    public function workflowList($userId, $where, $paging)
    {
        $stat = \App\Eloquent\Oa\Workflow::with('creatorInfo')
            ->orderBy('updated_at', 'desc');

        // 筛选
        if (!empty($where['oa_company_id'])) $stat->where('oa_company_id', '=', $where['oa_company_id']);
        if (!empty($where['related_type'])) $stat->where('related_type', '=', $where['related_type']);
        if (!empty($where['creator_id'])) $stat->where('creator_id', '=', $where['creator_id']);
        if (!empty($where['not_creator_id'])) $stat->where('creator_id', '!=', $where['not_creator_id']);
        if (!empty($where['dispose_code'])) $stat->where('dispose_code', '=', $where['dispose_code']);
        if (isset($where['is_workflow_end']) && $where['is_workflow_end'] === 0) {
            $stat->where('dispose_code', '!=', 1100);
            $stat->where('dispose_code', '!=', 1200);
            $stat->where('dispose_code', '!=', 1201);
        }
        if (!empty($where['assignee_id'])) $stat->where('assignee_id', '=', $where['assignee_id']);
        if (!empty($where['log_assignee_id'])) $stat->whereHas('workflowLogList', function ($q) use ($where) {
            $q->where('assignee_id', '=', $where['log_assignee_id']);
        });
        if (!empty($where['log_operator_id'])) $stat->whereHas('workflowLogList', function ($q) use ($where) {
            $q->where('operator_id', '=', $where['log_operator_id']);
        });
        if (!empty($where['copy_to_id'])) $stat->whereHas('workflowCopyList', function ($q) use ($where) {
            $q->where('copy_to_id', '=', $where['copy_to_id']);
        });

        // 分页
        $totalRow = $stat->count();
        if (!empty($paging['page']) && !empty($paging['page_size'])) {
            $stat->forPage($paging['page'], $paging['page_size']);
        }

        $list = $stat->get();
        foreach ($list as $item) {
//            switch ($item['related_type']) {
//                case 1:
//                    $item['related_type_str'] = '公文流程';
//                    unset($item['documentFlowInfo']);
//                    break;
//                case 2:
//                    $item['related_type_str'] = '请假流程';
//                    unset($item['leaveFlowInfo']);
//                    break;
//                case 3:
//                    $item['related_type_str'] = '用章流程';
//                    // todo
//                    break;
//                case 4:
//                    $item['related_type_str'] = '用车流程';
//                    // todo
//                    break;
//                case 5:
//                    $item['related_type_str'] = '离职流程';
//                    // todo
//                    break;
//                case 6:
//                    $item['related_type_str'] = '岗位调动流程';
//                    // todo
//                    break;
//                case 7:
//                    $item['related_type_str'] = '报销流程';
//                    // todo
//                    break;
//                case 8:
//                    $item['related_type_str'] = '外出流程';
//                    // todo
//                    break;
//                case 9:
//                    $item['related_type_str'] = '出差流程';
//                    // todo
//                    break;
//                case 10:
//                    $item['related_type_str'] = '调休流程';
//                    // todo
//                    break;
//                case 11:
//                    $item['related_type_str'] = '补勤流程';
//                    // todo
//                    break;
//                default:
//                    xThrow(ERR_LOGIC, '无法处理的流程');
//            }
            $item['related_type_str'] = self::getRelatedTypeStr($item['related_type']);
            $item['creator_name'] = $item['creator_id'] == 0 ? 'admin' : $item['creatorInfo']['name'];
            $item['created_at_str'] = $item['created_at']->format('Y-m-d H:i');
            $item['dispose_code_str'] = WorkflowDict::getDescriptionByDisposeCode($item['dispose_code']);
            unset($item['creatorInfo']);
        }

        return [
            'list' => $list,
            'totalRow' => $totalRow,
            'pageCurrent' => $paging['page']
        ];
    }

    /**
     * 详情
     * @author LuLingFeng
     * @param int $userId 用户ID
     * @param int $workflowId 详情ID
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function detail($userId, $workflowId)
    {
        $workflow = \App\Eloquent\Oa\Workflow::with(['workflowLogList.operatorInfo',
            'workflowLogList.assigneeInfo', 'workflowLogList.fileList', 'creatorInfo', 'flowFileList'])
            ->find($workflowId);
        if (empty($workflow)) xThrow(ERR_PARAMETER, '该流程信息不存在');
        switch ($workflow['related_type']) {
            case 1:
                $workflow['flow_info'] = $workflow['documentFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_DOCUMENT;
                unset($workflow['documentFlowInfo']);
                break;
            case 2:
                $workflow['leaveFlowInfo']['start_time_str'] = date('Y-m-d', $workflow['leaveFlowInfo']['start_time']);
                $workflow['leaveFlowInfo']['end_time_str'] = date('Y-m-d', $workflow['leaveFlowInfo']['end_time']);
                $workflow['leaveFlowInfo']['type_str'] = Flow::getLeaveTypeStr($workflow['leaveFlowInfo']['type']);
                $workflow['flow_info'] = $workflow['leaveFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_LEAVE;
                unset($workflow['leaveFlowInfo']);
                break;
            case 3:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_SEAL_USE;
                $workflow['sealFlowInfo']['department_name'] = $workflow['sealFlowInfo']['departmentInfo']['name'];
                unset($workflow['sealFlowInfo']['departmentInfo']);
                $workflow['sealFlowInfo']['file_type_str'] = Flow::getSealFileTypeStr($workflow['sealFlowInfo']['file_type']);
                $workflow['sealFlowInfo']['seal_type_str'] = Flow::getSealTypeStr($workflow['sealFlowInfo']['seal_type']);
                $workflow['flow_info'] = $workflow['sealFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow['sealFlowInfo']);
                break;
            case 4:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_CAR_USE;
                count($workflow['carFlowInfo']['flowCarVehicleList']);  // 触发读取
                $workflow['carFlowInfo']['department_name'] = $workflow['carFlowInfo']['departmentInfo']['name'];
                unset($workflow['carFlowInfo']['departmentInfo']);
                $workflow['carFlowInfo']['start_time_str'] = date('Y-m-d H:i', $workflow['carFlowInfo']['start_time']);
                $workflow['carFlowInfo']['return_time_str'] = date('Y-m-d H:i', $workflow['carFlowInfo']['return_time']);
                $workflow['flow_info'] = $workflow['carFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                foreach ($workflow['flow_info']['flowCarVehicleList'] as $flowCarVehicle) {
                    $temp = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_branch_id', $flowCarVehicle->id]])->get();
                    foreach ($temp as $value) {
                        $value->url = env('APP_URL') . $value->url;
                    }
                    $flowCarVehicle->file_list = $temp;
                }
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow['carFlowInfo']);
                break;
//            case 5:
//                $item['related_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_RESIGN;
//                // todo
//                break;
            case 6:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_TRANSFER_POST;
                $userInfo = new Personnel();
                $userInfo = $userInfo->getEmployeeInfo($workflow['creator_id']);
                $content['name'] = $userInfo->name;
                $content['employee_number'] = $userInfo->employee_number;
                $content['credential_number'] = $userInfo->credential_number;
                $content['department_name'] = $userInfo->department_name;
                $content['position'] = $userInfo->position;
                $content['entry_time'] = $userInfo->entry_time;
                $content['working_years'] = $userInfo->working_years;
                $content['adjust_time_str'] = date('Y-m-d', $workflow['transferPostFlowInfo']['adjust_time']);
                $flow_info = $workflow['transferPostFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = array_merge($flow_info, $content);
                unset($workflow->transferPostFlowInfo);
                break;
            case 7:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_REIMBURSE;
                count($workflow['reimburseFlowInfo']['reimburseItemList']);  // 触发读取
                $workflow['flow_info'] = $workflow['reimburseFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                foreach ($workflow['flow_info']['reimburseItemList'] as $reimburseItem) {
                    $temp = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_branch_id', $reimburseItem->id]])->get();
                    foreach ($temp as $value) {
                        $value->url = env('APP_URL') . $value->url;
                    }
                    $reimburseItem->file_list = $temp;
                }
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->reimburseFlowInfo);
                break;
            case 8:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_EGRESS;
                $workflow['goOutFlowInfo']['start_time_str'] = date('Y-m-d', $workflow['goOutFlowInfo']['start_time']);
                $workflow['goOutFlowInfo']['end_time_str'] = date('Y-m-d', $workflow['goOutFlowInfo']['end_time']);
                $workflow['flow_info'] = $workflow['goOutFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->goOutFlowInfo);
                break;
            case 9:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_BUSINESS_TRIP;
                foreach ($workflow['businessTripFlowInfo']['travelList'] as $travel) {
                    $travel['start_time_str'] = date('Y-m-d', $travel['start_time']);
                    $travel['end_time_str'] = date('Y-m-d', $travel['end_time']);
                }
                $workflow['flow_info'] = $workflow['businessTripFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->businessTripFlowInfo);
                break;
            case 10:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_HOLIDAY_SHIFT;
                $workflow['daysOffFlowInfo']['start_time_str'] = date('Y-m-d', $workflow['daysOffFlowInfo']['start_time']);
                $workflow['daysOffFlowInfo']['end_time_str'] = date('Y-m-d', $workflow['daysOffFlowInfo']['end_time']);
                $workflow['flow_info'] = $workflow['daysOffFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->daysOffFlowInfo);
                break;
            case 11:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_WORKDAY_SHIT;
                $workflow['supplementFlowInfo']['time_str'] = date('Y-m-d', $workflow['supplementFlowInfo']['time']);
                $workflow['flow_info'] = $workflow['supplementFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->supplementFlowInfo);
                break;
            case 12:
                $workflow['relate_type_abbr'] = Flow::RELATE_TYPE_ABBR_FLOW_OVERTIME_PAY;
                $workflow['supplementFlowInfo']['time_str'] = date('Y-m-d', $workflow['supplementFlowInfo']['time']);
                $workflow['flow_info'] = $workflow['supplementFlowInfo'];
                $fileList = FlowFile::where([['oa_workflow_id', $workflowId], ['oa_flow_master_id', $workflow['flow_info']->id]])->get();
                foreach ($fileList as $file) {
                    $file->url = env('APP_URL') . $file->url;
                }
                $workflow['flow_info']->file_list = $fileList;
                $workflow['flow_info'] = $workflow['flow_info']->toArray();
                unset($workflow->supplementFlowInfo);
                break;
            default:
                xThrow(ERR_LOGIC, '无法处理的流程');
        }
        $workflow['creator_name'] = $workflow['creator_id'] == 0 ? 'admin' : $workflow['creatorInfo']['name'];
        $workflow['created_at_str'] = $workflow['created_at']->format('Y-m-d H:i');
        $workflow['dispose_code_str'] = WorkflowDict::getDescriptionByDisposeCode($workflow['dispose_code']);
        foreach ($workflow['workflowLogList'] as $log) {
            $log['operator_name'] = $log['operator_id'] == 0 ? 'admin' : $log['operatorInfo']['name'];
            $log['assignee_name'] = $log['assignee_id'] == 0 ? 'admin' : $log['assigneeInfo']['name'];
            $log['created_at_str'] = $log['created_at']->format('Y-m-d H:i');
            unset($log['operatorInfo'], $log['assigneeInfo']);
            $imageList = [];
            $enclosureList = [];
            foreach ($log['fileList'] as $file) {
                if ($file['type'] == 1) {
                    $imageList[] = env('APP_URL') . $file['url'];
                } elseif ($file['type'] == 2) {
                    $enclosureList[] = env('APP_URL') . $file['url'];
                }
            }
            $log['image_list'] = $imageList;
            $log['enclosure_list'] = $enclosureList;
            unset($log['fileList']);
        }
//        // 附件
//        $workflow['flow_info']->file_list = collect();
//        foreach ($workflow['flowFileList'] as $file) {
//            if ($file['oa_flow_branch_id'] == 0) {
//                $workflow['flow_info']->file_list[] = $file->toArray();
//            } else {
//                if($workflow['flow_info']->reimburseItemList) {
//                    foreach ($workflow['flow_info']->reimburseItemList as $reimburseItem){
//                        if($reimburseItem->id == $file['oa_flow_branch_id']) {
//                            $reimburseItem->file_list[] = $file->toArray();
//                        }
//                    }
//                } else if($workflow['flow_info']->flowCarVehicleList) {
//                    foreach ($workflow['flow_info']->flowCarVehicleList as $flowCarVehicle){
//                        if($flowCarVehicle->id == $file['oa_flow_branch_id']) {
//                            $flowCarVehicle->file_list[] = $file->toArray();
//                        }
//                    }
//                }
//
//            }
//        }
//        $workflow['flow_info'] = $workflow['flow_info']->toArray();
//        echo '<pre>';
//        var_dump($workflow['flow_info']);exit;
        $workflow['title'] = $workflow['creatorInfo']['name'] . '的'
            . \App\Http\Admin\Administration\Models\Workflow::getRelatedTypeStr($workflow['related_type']);
        unset($workflow['creatorInfo']);

        // 能否操作
        $workflow['is_able_to_handle'] = 0;
        if ($userId === 0 || $workflow['assignee_id'] == $userId) {
            if ($workflow['dispose_code'] != 1200 && $workflow['dispose_code'] != 1100)
                $workflow['is_able_to_handle'] = 1;
        }
        return $workflow;
    }

    public function getFileList($flowId)
    {
        $fileList = FlowFile::where('flow_id', '=', $flowId)
            ->get();
    }

    /**
     * 流程类型描述
     * @author LuLingFeng
     * @param $type
     * @return string
     */
    public static function getRelatedTypeStr($type)
    {
        $str = '未知';
        switch ($type) {
            case 1:
                $str = '公文';
                break;
            case 2:
                $str = '请假';
                break;
            case 3:
                $str = '用章';
                break;
            case 4:
                $str = '用车';
                break;
            case 5:
                $str = '离职';
                break;
            case 6:
                $str = '岗位调动';
                break;
            case 7:
                $str = '报销';
                break;
            case 8:
                $str = '外出';
                break;
            case 9:
                $str = '出差';
                break;
            case 10:
                $str = '调休';
                break;
            case 11:
                $str = '补勤';
                break;
            case 12:
                $str = '加班费';
                break;
            case 13:
                $str = '领用申请';
                break;
            case 14:
                $str = '采购';
                break;
            case 15:
                $str = '合同';
                break;
            case 16:
                $str = '备用金';
                break;
            case 17:
                $str = '制度方案';
                break;
            case 18:
                $str = '招聘需求';
                break;
            case 19:
                $str = '奖罚申报';
                break;
            case 20:
                $str = '离职';
                break;
            case 21:
                $str = '转正晋升调薪';
                break;
            case 22:
                $str = '补签';
                break;
            case 23:
                $str = '面试';
                break;
            case 24:
                $str = '入职';
                break;
            case 26:
                $str = '采购申请';
                break;
            case 27:
                $str = '退货申请';
                break;
        }
        return $str . '流程';
    }
}